package de.idgard.android.addon.ui.dialogs;

import android.app.Dialog;
import android.content.Context;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.TextView;
import de.idgard.android.R;
import de.idgard.android.addon.services.GlobalServiceRegistry;
import de.idgard.android.addon.ui.services.LayoutAdjustmentService;
import de.idgard.android.addon.ui.services.impl.UIServiceRegistry;

public class IDGardUpdateDialog extends Dialog {

	private LayoutAdjustmentService getLayoutAdjustmentService() {
		return UIServiceRegistry.instance().getlayouAdjustmentService();
	}

	private Button btnUpdateClose, btnDownloadUpdate;
	private TextView tvUpdateInfo;


	public IDGardUpdateDialog(Context context, String givenlatestVersionLink) {
		super(context);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.idgard_dialog_updates);
		
		int width = getLayoutAdjustmentService().getScreenWidth();
		width = width * 90 / 100;
		getLayoutAdjustmentService().adjustDialogLayout(this, -1, width, -1, -1);

		tvUpdateInfo = (TextView) findViewById(R.id.tv_update_info);
		btnUpdateClose = (Button) findViewById(R.id.btn_update_close);
		btnDownloadUpdate = (Button) findViewById(R.id.btn_download_update);
		
		final String latestVersionLink;
		if (givenlatestVersionLink == null) {
			latestVersionLink = GlobalServiceRegistry.instance()
					.getUpdateService().checkIfLatestVersionAndGetLinkUrl();
		} else {
			latestVersionLink = givenlatestVersionLink;
		}

		if (latestVersionLink == null) {
			tvUpdateInfo.setText(R.string.latestVersion);
			btnDownloadUpdate.setEnabled(false);
		} 
		else {
			tvUpdateInfo.setText(R.string.updateTolatestVersion);
			btnDownloadUpdate.setOnClickListener(new View.OnClickListener() {
				
				@Override
				public void onClick(View v) {
					GlobalServiceRegistry.instance().getZircoToIDGardAPI()
					.navigateToUrl(latestVersionLink);
			        dismiss();
				}
			});
		}
		
		btnUpdateClose.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				dismiss();
			}
		});

	}

}
